// miniprogram/pages/poetry/mark/mark.js
const poetry_db = wx.cloud.database().collection("poetry")
Page({

  data: {
    poetryList: [],
    poetrys: [],
    curPage: 1,
    isRank: true,
    pages: [1, 2, 3, 4, 5, '下一页']
  },
  onLoad: function (options) {
    var optitle = options.title
    var condition = {
      title: "诗词排行榜"
    }
    if (optitle != null) {
      console.log(options.title)
      wx.setNavigationBarTitle({
        title: optitle
      })
      condition = {
        title: optitle
      }
      this.setData({
        isRank: false
      })
    }
    var _this = this
    poetry_db.where(condition).get({
      success: function (res) {
        console.log(res)
        var poetrys = res.data[0].poetrys
        _this.setData({
          poetrys: poetrys.slice(0, 10),
          poetryList: poetrys
        })
      }
    })
  },
  //页面点击监听
  onIndexClick(e) {
    console.log(e)
    var pages = this.data.pages
    var curPage = this.data.curPage
    var poetryList = this.data.poetryList
    var value = e.currentTarget.dataset.value
    var remainPoes = poetryList.length - 10 * pages[4]
    // console.log("remainPoes", remainPoes)
    // 点击的是最有一个页码
    var clickLastPage = value == pages[4].toString()
    // 点击"下一页"到最后一个页码
    var nextToLastPage = value == "下一页" && curPage == pages[3]
    if (remainPoes < 0 && (clickLastPage || nextToLastPage)) {
      wx.showToast({
        title: '暂无更多数据'
      })
      return;
    }
    curPage = value != '下一页' ? value : curPage + 1
    if (curPage == pages[4] && curPage < 20) {
      var arr = [curPage + 1, curPage + 2]
      pages.splice(0, 2)
      pages.splice(3, 0, arr[0], arr[1])
    }
    if (curPage == pages[0] && curPage > 1) {
      var arr = [curPage - 2, curPage - 1]
      pages.splice(3, 2)
      pages.splice(0, 0, arr[0], arr[1])
    }
    var start = (curPage - 1) * 10
    // console.log(poetryList, start)
    var poetrys = poetryList.slice(start, start + 10)
    this.pageScrollToTop()
    this.setData({
      curPage: curPage,
      pages: pages,
      poetrys: poetrys
    })
  },
  // 使页面滚动到容器顶部
  pageScrollToTop: function () {
    wx.createSelectorQuery().select('.poetrys-list').boundingClientRect(function (rect) {
      console.log(rect.height);
      wx.pageScrollTo({
        scrollTop: 0
      })
    }).exec()
  },
  //诗词item点击监听
  onPoetryItemClick(e) {
    console.log(e)
    var poetryList = this.data.poetryList
    var index = e.currentTarget.dataset.index
    var poetry = JSON.stringify(poetryList[index])
    // console.log(poetry)
    wx.navigateTo({
      url: '../detail/detail?poetry=' + encodeURIComponent(poetry)
    })
  }
})